package com.lxj.util;


import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import redis.clients.jedis.Jedis;


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "http://localhost:8081");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        //对于某些页面是不需要登录的  控制只要后台才必须登录；
        //访问有back的需要登陆
        String url = request.getRequestURI();
        System.out.println(url);
        if (url.startsWith("/html/")) {
            Cookie[] cookies = request.getCookies();
            String un = "";
            for (Cookie cookie : cookies) {
                System.out.println(cookie.getValue());
                System.out.println(cookie.getName());
                un = cookie.getValue();
            }
            if (un != null) {
                Jedis jedis = new Jedis();
                String username = jedis.get(un);
                if (username == null) {
                    return false;
                }
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

}
